import { DownloadOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import { getDownloadTemplateFile } from '../service';

const handleType = (type: string): { btnText: string; urlType: string } => {
  switch (type) {
    case 'lot':
      return {
        btnText: '路段创建模板文件',
        urlType: 'create_parkinglot',
      };
    case 'bind_sensor':
      return {
        btnText: '泊位地磁绑定模板文件',
        urlType: 'bind_sensor',
      };
    case 'spot':
      return {
        btnText: '泊位创建模板文件',
        urlType: 'create_parkingspot',
      };
    case 'create_sensor':
      return {
        btnText: '地磁设备创建模板文件',
        urlType: 'create_sensor_device',
      };
    case 'create_patrol':
      return {
        btnText: '巡检设备创建模板文件',
        urlType: 'create_patrol_device',
      };
    case 'import_order_m100':
      return {
        btnText: '欠费订单导入模板文件',
        urlType: 'import_order_m100',
      };
    case 'import_order':
      return {
        btnText: '欠费订单导入模板文件',
        urlType: 'import_order',
      };
    default:
      return {
        btnText: '',
        urlType: '',
      };
  }
};

export default (props: { type: string }) => {
  const { btnText, urlType } = handleType(props.type);

  return (
    <Button
      style={{
        marginRight: '5px',
        marginTop: '3px',
      }}
      onClick={async () => {
        const res = await getDownloadTemplateFile(urlType);
        try {
          if (res) {
            const filename = `multi_${urlType}.xlsx`;
            const downloadElement = document.createElement('a');
            const herf = window.URL.createObjectURL(
              new Blob([res], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
              }),
            );
            downloadElement.href = herf;
            downloadElement.download = filename;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(herf); // 释放blob对象
            return true;
          }
          message.error({ content: res?.message || '下载失败', key: 'd_template' });
          return false;
        } catch (err) {
          message.error({ content: String(err), key: 'd_template' });
          return false;
        }
      }}
    >
      <DownloadOutlined />
      {btnText}
    </Button>
  );
};
